package com.tianya.portal.file.controller;

import java.net.URL;

import com.tianya.common.web.exception.BusinessException;
import com.tianya.portal.common.utils.AsposeCellsUtils;
import com.tianya.portal.common.utils.AsposeWordUtils;
import com.tianya.portal.common.utils.file.FileUtils;
import com.tianya.portal.common.utils.file.MimeTypeUtils;
import com.tianya.portal.file.service.IFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Arrays;

@RestController
@RequestMapping("/file")
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private IFileService sysFileService;


    /**
     * 通用下载请求
     *
     * @param oldName 文件原名称
     * @param path    文件路径
     */
    @GetMapping("/download")
    public void fileDownload(String oldName, String path, String bucketName, HttpServletResponse httpResponse,
                             HttpServletRequest request) {
        try {
            InputStream inputStream = sysFileService.downloadFiles(path, bucketName);
            byte buf[] = new byte[1024];
            int length = 0;
            httpResponse.reset();
            httpResponse.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(oldName, "UTF-8"));
            httpResponse.setContentType("application/octet-stream");
            httpResponse.setCharacterEncoding("utf-8");
            httpResponse.setHeader("Accept-Ranges", "bytes");
            OutputStream outputStream = httpResponse.getOutputStream();
            while ((length = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            outputStream.close();
        } catch (java.lang.Exception ex) {
            log.error("文件下载失败", ex.getMessage());
        }
    }

    /**
     * 文件预览
     */
    @PostMapping("/preview")
    public void filePreview(MultipartFile file, HttpServletResponse httpResponse,
                            HttpServletRequest request) {
        //判断文件类型
        String extensionName = FileUtils.getExtensionName(file.getOriginalFilename());
        if (!Arrays.asList(MimeTypeUtils.ALLOWED_PREVIEW_EXTENSION).contains(extensionName)) {
            throw new BusinessException("暂不支持此类型文件");
        }
        try {
            InputStream inputStream = file.getInputStream();
            byte bytes[] = new byte[1024];
            int length = 0;
            httpResponse.reset();
            OutputStream outputStream = httpResponse.getOutputStream();
            String nowFileName = file.getOriginalFilename().replace("." + extensionName, ".pdf");
            if (Arrays.asList(MimeTypeUtils.WORD_EXTENSION).contains(extensionName)) {
                httpResponse.setHeader("Content-Disposition",
                        "inline;filename=" + URLEncoder.encode(nowFileName, "UTF-8"));
                httpResponse.setCharacterEncoding("utf-8");
                httpResponse.setContentType("application/pdf");
                inputStream = AsposeWordUtils.getWordToPdf(inputStream);
            }
            if (Arrays.asList(MimeTypeUtils.CELL_EXTENSION).contains(extensionName)) {
                httpResponse.setHeader("Content-Disposition",
                        "inline;filename=" + URLEncoder.encode(nowFileName, "UTF-8"));
                httpResponse.setCharacterEncoding("utf-8");
                httpResponse.setContentType("application/pdf");
                inputStream = AsposeCellsUtils.getCellToPdf(inputStream);
            }
            while ((length = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, length);
            }
            outputStream.flush();
            outputStream.close();

        } catch (Exception ex) {
            log.error("文件预览失败", ex.getMessage());
        }
    }

    /**
     * 远程文件预览
     */
    @PostMapping("/previewUrl")
    public void filePreviewUrl(String url, HttpServletResponse httpResponse,
                               HttpServletRequest request) {
        //判断文件类型
        String[] splits = url.split("/");
        String fileName = splits[splits.length - 1];
        String extensionName = FileUtils.getExtensionName(fileName);
        if (!Arrays.asList(MimeTypeUtils.ALLOWED_PREVIEW_EXTENSION).contains(extensionName)) {
            throw new BusinessException("暂不支持此类型文件");
        }
        try {
            URL connect = new URL(url);
            URLConnection urlConnection = connect.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            byte bytes[] = new byte[1024];
            int length = 0;
            httpResponse.reset();
            OutputStream outputStream = httpResponse.getOutputStream();

            String nowFileName = fileName.replace("." + extensionName, ".pdf");
            if (Arrays.asList(MimeTypeUtils.WORD_EXTENSION).contains(extensionName)) {
                httpResponse.setHeader("Content-Disposition",
                        "inline;filename=" + URLEncoder.encode(nowFileName, "UTF-8"));
                httpResponse.setCharacterEncoding("utf-8");
                httpResponse.setContentType("application/pdf");
                inputStream = AsposeWordUtils.getWordToPdf(inputStream);
            }
            if (Arrays.asList(MimeTypeUtils.CELL_EXTENSION).contains(extensionName)) {
                httpResponse.setHeader("Content-Disposition",
                        "inline;filename=" + URLEncoder.encode(nowFileName, "UTF-8"));
                httpResponse.setCharacterEncoding("utf-8");
                httpResponse.setContentType("application/pdf");
                inputStream = AsposeCellsUtils.getCellToPdf(inputStream);
            }
            while ((length = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, length);
            }
            outputStream.flush();
            outputStream.close();

        } catch (Exception ex) {
            log.error("文件预览失败", ex.getMessage());
        }
    }
}
